<script setup>
import { onMounted, nextTick, ref, reactive, watch } from "vue";
import { Expand } from "@element-plus/icons-vue";
import { currentYBD } from "../../stores/default";
import Difang from "../forecast/Difang.vue";
import mitt from "../../assets/js/mitt";
import {
  initList,
  getDetail,
  lookFore,
  hours,
  updateFore,
  getForeTable,
} from "../forecast/fore";
import yuanHong from "@/assets/img/圆66872.png";
import yuanLan from "@/assets/img/yuanlan.png";
import yuanLv from "@/assets/img/yuanlv.png";
import ComPdfW from "@/components/ComPdfW.vue";
import { ElMessage } from "element-plus";
import Fore from "../forecast/Fore.vue";

const url = import.meta.env.VITE_backurl;

onMounted(() => {
  dateValue.value = new Date()
    .toLocaleDateString()
    .split("/")
    .map((item) => {
      return item.length < 2 ? "0" + item : item;
    })
    .join("-");
  handleInitList();
});
const dateValue = ref("");

const editYBD = currentYBD();
const listValue = ref([]),
  styKun = reactive({
    background: "var(--el-color-Fill-Light)",
  }),
  isList = ref(true);

const showList = () => {
  isList.value = !isList.value;
};

const dateChange = (value) => {
  // console.log(value);
  handleInitList();
};

const updateStatus = (data) => {
  if (data.tag == "yl") {
    handleLookFore("yl");
    return;
  }
  if (listValue.value[0].status != 2 && data.status) {
    listValue.value[0].status = data.status;
  }
};

const subFore = () => {
  mitt.emit("subFore", {
    id: listValue.value[0].id,
    time: dateValue.value,
  });
};

const handleInitList = () => {
  initList({
    time: dateValue.value,
  })
    .then((res) => {
      listValue.value = res.data.data
        .filter((item) => item.code == "zb")
        .map((item) => {
          return {
            id: item.id,
            name: item.name,
            status: item.status,
            code: item.code,
          };
        });
      mitt.emit("getDetail", {
        id: listValue.value[0].id,
        time: dateValue.value,
        type: "zb",
        status: listValue.value[0].status,
        code: listValue.value[0].code,
      });
    })
    .catch((err) => {
      ElMessage.error(err);
    });
};

const content1 = ref(""),
  content2 = ref("");

const sendContent = (data) => {
  if (data) {
    content1.value = data[0];
    content2.value = data[1];
  } else {
    content1.value = "";
    content2.value = "";
  }
};

const handleCreateFore = (tag = "") => {
  const currentYBD = editYBD.getValue;
  if (listValue.value[currentYBD].status == 0) {
    ElMessage({
      message: "预报单未提交",
      type: "warning",
    });
    return;
  }
  // console.log(listValue.value[currentYBD]);
  let type = "zb";

  mitt.emit("createFore", {
    id: listValue.value[currentYBD].id,
    time: dateValue.value,
    hour: currentHour.value,
    type: type,
    tag: tag,
  });
};

const handleLookFore = (tag = "") => {
  if (tag != "yl") {
    // ElMessage({
    //   message: '预报单未生成',
    //   type: 'warning'
    // })
    handleCreateFore("yl");
    return;
  }
  lookFore({
    name:
      listValue.value[editYBD.getValue].name +
      dateValue.value.split("-").join("") +
      ".pdf",
  })
    .then((res) => {
      urlObj = res.data;
      setTimeout(() => {
        pdfDialog.value = true;
      }, 0);
    })
    .catch((err) => {
      ElMessage.error(err);
    });
};

const handleDownload = (type) => {
  getForeTable({
    id: listValue.value[editYBD.getValue].id,
    time: dateValue.value,
  })
    .then((res) => {
      if (res.data.data.fileName != "") {
        let fileName =
          listValue.value[editYBD.getValue].name +
          dateValue.value.split("-").join("") +
          "." +
          type;
        lookFore({
          name: fileName,
        })
          .then((res) => {
            const a = document.createElement("a");
            a.href = URL.createObjectURL(res.data);
            a.download = fileName;
            a.click();
          })
          .catch((err) => {
            ElMessage.error(err);
          });
      } else {
        ElMessage({
          message: "预报单未生成",
          type: "error",
        });
      }
    })
    .catch((err) => {
      ElMessage.error(err);
    });
  // if (listValue.value[editYBD.getValue].status != 2) {
  //   ElMessage({
  //     message: '预报单未生成',
  //     type: 'warning'
  //   })
  //   return
  // }
  // let fileName = listValue.value[editYBD.getValue].name + dateValue.value.split('-').join('') + '.' + type
  // lookFore({
  //   name: fileName,
  // })
  //   .then(res => {
  //     const a = document.createElement('a')
  //     a.href = URL.createObjectURL(res.data)
  //     a.download = fileName
  //     a.click()
  //   })
  //   .catch(err => {
  //     ElMessage.error(err)
  //   })
};

const yuanImg = (state) => {
  if (state == 0) {
    return yuanHong;
  } else if (state == 1) {
    return yuanLan;
  } else {
    return yuanLv;
  }
};

const tips = ref([
  {
    content: "未提交",
    src: yuanHong,
  },
  {
    content: "已提交",
    src: yuanLan,
  },
  {
    content: "已生成",
    src: yuanLv,
  },
]);

const currentHour = ref("15");

let urlObj = {};
const pdfDialog = ref(false);

const getState = (state) => {
  if (state == 0) {
    return {
      type: "danger",
      text: "未保存",
    };
  } else if (state == 1) {
    return {
      type: "warning",
      text: "已保存",
    };
  } else if (state == 2) {
    return {
      type: "success",
      text: "已发送",
    };
  }
  // else{
  //   return {
  //     type: 'success',
  //     text: '已生成'
  //   }
  // }
};

const sendFore = () => {
    if (listValue.value[editYBD.getValue].status == 0) {
      ElMessage({
        message: "预报单未保存",
        type: "error",
      });
      return;
    }
    // 如果是已发送状态，选择是否重新发送
    if (listValue.value[editYBD.getValue].status == 2) {
      ElMessageBox.confirm("是否重新发送预报单？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          confirmSend();
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "已取消发送",
          });
        });
    } else {
      confirmSend();
    }
  },
  confirmSend = () => {
    updateFore({
      id: listValue.value[editYBD.getValue].id,
      time: dateValue.value,
      state: 2,
    })
      .then((res) => {
        ElMessage({
          message: "发送成功",
          type: "success",
        });
        listValue.value[editYBD.getValue].status = 2;
      })
      .catch((err) => {
        ElMessage.error(err);
      });
  };
</script>

<template>
  <div class="WeekFore">
    <Fore :keys="['zb']" />
    <template v-if="false">
      <!-- 用于切换的按钮 -->
      <Transition name="fade_start" mode="out-in">
        <img
          src="/img/biaodan.png"
          alt=""
          style="height: 20px; width: 20px; cursor: pointer; margin: 10px"
          @click="showList"
          v-show="!isList"
        />
      </Transition>
      <!-- 周报列表 -->
      <Transition name="expand" mode="out-in">
        <div class="list_left" v-show="isList">
          <div class="card_hook">
            <div
              class="card_header"
              style="
                margin-left: 15px;
                height: 45px;
                display: flex;
                align-items: center;
              "
            >
              <img
                src="/img/biaodan.png"
                alt=""
                style="height: 20px; width: 20px; cursor: pointer"
                @click="showList"
              />
              <span style="margin-left: 10px; font-size: 20px">周报列表</span>
              <!-- <div style="margin-left: auto;margin-right: 0px;">
              <el-tooltip v-for="item in tips" :content="item.content" placement="top" effect="light">
                <img class="yuanTip" :src="item.src" alt="">
              </el-tooltip>
            </div> -->
            </div>
            <el-row
              v-for="(item, idx) in listValue"
              :style="idx % 2 == 0 ? styKun : ''"
            >
              <el-col :span="24">
                <div
                  style="
                    font-size: 16px;
                    display: flex;
                    align-items: center;
                    padding-left: 15px;
                    width: 100%;
                  "
                >
                  <!-- <img :src="yuanImg(item.status)" alt="" style="height: 18px;width: 18px;"> -->
                  <el-tag
                    class="ml-2"
                    :type="getState(item.status).type"
                    style="font-family: '得意黑体'"
                    >{{ getState(item.status).text }}</el-tag
                  >
                  <span
                    style="
                      margin-left: 10px;
                      height: 100%;
                      font-family: '钉钉进步体';
                      font-size: 18px;
                    "
                    >{{ item.name }}</span
                  >
                  <el-tooltip
                    class="box-item"
                    effect="light"
                    content="正在处理"
                    placement="bottom-start"
                  >
                    <Transition name="fade_start" mode="out-in">
                      <img
                        src="/img/zhengzai.png"
                        alt=""
                        v-show="idx == editYBD.getValue"
                        style="
                          height: 16px;
                          width: 16px;
                          margin-left: auto;
                          margin-right: 20px;
                        "
                      />
                    </Transition>
                  </el-tooltip>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>
      </Transition>
      <!-- 主要内容 -->
      <div id="content">
        <!-- 工具条 -->
        <div class="card_hook content_tool">
          <el-row :gutter="15" class="home-card-one mb15">
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="6">
              <div style="font-family: '得意黑体'; font-size: 16px">
                当前预报单：<span
                  style="color: var(--el-color-primary); font-size: 18px"
                >
                  <!-- {{ listValue[editYBD.getValue]?.name}} -->
                  浅滩一周海洋环境预报
                </span>
              </div>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="6">
              <!-- 日期选择器和上传文件 -->
              <span style="font-family: '得意黑体'; font-size: 16px"
                >填报日期：</span
              >
              <el-date-picker
                v-model="dateValue"
                type="date"
                placeholder="选择填报日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                @change="dateChange"
              />
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="6">
              <!-- 日期选择器和上传文件 -->
              <span style="font-family: '得意黑体'; font-size: 16px"
                >填报时间：</span
              >
              <el-select v-model="currentHour" class="m-2" placeholder="Select">
                <el-option
                  v-for="item in hours"
                  :key="item.label"
                  :label="item.label"
                  :value="item.label"
                />
              </el-select>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="6">
              <!-- 提交和生成预报单按钮 -->
              <div>
                <el-button type="" size="default" @click="subFore"
                  >保存</el-button
                >
                <el-button type="info" size="default" @click="handleLookFore"
                  >预览</el-button
                >
                <el-button type="primary" size="default" @click="sendFore"
                  >发布</el-button
                >
                <el-button
                  type="success"
                  size="default"
                  @click="handleCreateFore"
                  >生成预报单</el-button
                >
                <el-popconfirm
                  title="选择下载类型"
                  confirm-button-text="docx"
                  cancel-button-text="pdf"
                  @confirm="handleDownload('docx')"
                  @cancel="handleDownload('pdf')"
                >
                  <template #reference>
                    <el-button type="default">下载</el-button>
                  </template>
                </el-popconfirm>
              </div>
            </el-col>
          </el-row>
        </div>
        <!-- 核心的内容，那些表格 -->
        <div class="content_tem">
          <!-- <div class="card_hook" style="margin-top: 10px;">
          <el-input v-model="content1" :rows="2" type="textarea" placeholder="风暴潮、海浪预测分析内容" />
        </div>
        <div class="card_hook" style="margin-top: 10px;">
          <el-input v-model="content2" :rows="2" type="textarea" placeholder="露滩/漫滩时间预测分析内容" />
        </div> -->

          <Difang @updateStatus="updateStatus" @sendContent="sendContent" />
        </div>
      </div>
      <el-dialog
        class="pdfDialog"
        width="70%"
        v-model="pdfDialog"
        :destroy-on-close="true"
        :show-close="false"
        top="0vh"
      >
        <ComPdfW :urlObj="urlObj" style="height: 90vh" />
      </el-dialog>
    </template>
  </div>
</template>

<style lang="less" scoped>
.WeekFore {
  display: flex;
  width: 100%;
  height: 100%;

  :deep(.pdfDialog) {
    background-color: transparent !important;
    box-shadow: none !important;

    .el-dialog__body {
      padding: 0px !important;
    }
  }

  :deep(.docx-wrapper) {
    background-color: transparent !important;
    padding: 0px !important;
  }

  .list_left {
    width: 400px;
    height: 100%;
    // flex-shrink: 0;
    padding: 15px;
    // flex: 1;

    .card_hook {
      // height: 30%;
      height: 100%;
      padding: 10px;
      overflow: auto;

      .card_header {
        display: flex;

        .yuanTip {
          height: 25px;
          cursor: pointer;
        }
      }

      // &:hover {
      //   box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
      // }
      .el-row {
        // width: 100%;
        height: 40px;
        display: flex;
        align-items: center;
        cursor: pointer;

        .el-col {
          height: 100%;
          display: flex;
          align-items: center;

          .tool {
            margin-left: auto;
            margin-right: 20px;
            color: var(--el-color-primary); // #409eff;
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100%;
            cursor: pointer;
            user-select: none;
          }
        }
      }
    }
  }

  #showBtn {
    width: 20px;
    height: 20%;
    background: var(--el-color-primary);
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    // 上下居中
    margin-top: auto;
    margin-bottom: auto;
    // 向左偏移10px
    // transform: translateX(-15px);
    // 右上和右下圆角
    border-top-right-radius: 10px;
    border-bottom-right-radius: 10px;
  }

  #content {
    height: 100%;
    padding: 15px;
    padding-left: 2px;

    transition: all 0.3s;
    overflow: auto;
    flex: 1;

    .card_hook {
      width: 100%;
      padding: 10px 15px;
    }

    .content_tool {
      // min-height: 65px;
      display: flex;
      align-items: center;

      .el-row {
        width: 100%;
      }

      .upload-demo {
        display: flex;
      }

      .el-col {
        padding: 10px 10px;
        display: flex;
        align-items: center;
      }
    }

    .content_tem {
      flex: 1;
    }
  }

  .expand-enter-active {
    transition: all 0.35s ease;
  }

  .expand-enter-from,
  .expand-leave-to {
    // width: 0px;
    // flex: 0;
    opacity: 0;
    transform: translateX(-100%);
  }
}
</style>
